﻿using Callisto.Controls;
using CrmField.Win8App.Common;
using CrmField.Win8App.Data;
using CrmField.Win8App.UserControls;
using CRMField.Win8App.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.Connectivity;
using Windows.UI;
using Windows.UI.ApplicationSettings;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227

namespace CrmField.Win8App
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
            SuspensionManager.KnownTypes.Add(typeof(ActivityDataSource));

        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                        rootFrame.Content = null;
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            //Activating from Tile
            if ((!string.IsNullOrEmpty(args.TileId)) && (args.TileId != "App"))
            {
                rootFrame.Navigate(typeof(ItemDetailPage), Guid.Parse(args.TileId));
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(GroupedItemsPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            // Ensure the current window is active
            Window.Current.Activate();

            SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;
        }

        void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            SettingsCommand cmd = new SettingsCommand("CrmSettings", "CRM Connection Settings", (x) =>
            {
                // create a new instance of the flyout
                SettingsFlyout settings = new SettingsFlyout();

                // optionally change header and content background colors away from defaults (recommended);
                settings.HeaderBrush = new SolidColorBrush(Color.FromArgb(255, 16, 152, 205));
                settings.HeaderText = "CRM Connection Settings";
                settings.FlyoutWidth = SettingsFlyout.SettingsFlyoutWidth.Wide;

                // provide some logo (preferrably the smallogo the app uses)
                BitmapImage bmp = new BitmapImage(new Uri("ms-appx:///Assets/SmallLogo.png"));
                settings.SmallLogoImageSource = bmp;

                // set the content for the flyout        
                var panel = new CrmSettingsPanel();
                panel.Foreground = new SolidColorBrush(Colors.Black);
                settings.Content = new CrmSettingsPanel();
                settings.DataContext = CrmContextManager.Context;

                // open it
                settings.IsOpen = true;
            });

            args.Request.ApplicationCommands.Add(cmd);
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            SuspensionManager.SaveAsync();
            deferral.Complete();
        }

        public const string DataSourceName = "DataSourceServiceActivty";

        /// <summary>
        /// Invoked when the application is activated to display search results.
        /// </summary>
        /// <param name="args">Details about the activation request.</param>
        protected async override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args)
        {
            // TODO: Register the Windows.ApplicationModel.Search.SearchPane.GetForCurrentView().QuerySubmitted
            // event in OnWindowCreated to speed up searches once the application is already running

            // If the Window isn't already using Frame navigation, insert our own Frame
            var previousContent = Window.Current.Content;
            var frame = previousContent as Frame;

            // If the app does not contain a top-level frame, it is possible that this 
            // is the initial launch of the app. Typically this method and OnLaunched 
            // in App.xaml.cs can call a common method.
            if (frame == null)
            {
                // Create a Frame to act as the navigation context and associate it with
                // a SuspensionManager key
                frame = new Frame();
                CrmField.Win8App.Common.SuspensionManager.RegisterFrame(frame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await CrmField.Win8App.Common.SuspensionManager.RestoreAsync();
                    }
                    catch (CrmField.Win8App.Common.SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }
            }

            if (ActivityDataSource.CurrentDataSource == null)
            {
                try
                {
                    await ActivityDataSource.LoadFromFileOrService(App.DataSourceName);
                }
                catch (Exception ex)
                {
                    var messageDialog = new MessageDialog("Uppps... there was a problem trying to load data. \n" + ex.Message);
                    messageDialog.ShowAsync();
                }

            }
            frame.Navigate(typeof(SearchResultsPage), args.QueryText);
            Window.Current.Content = frame;

            // Ensure the current window is active
            Window.Current.Activate();
        }


        /// <summary>
        /// Check internet connectivity
        /// </summary>
        /// <returns>true if internet connectivity is available</returns>
        public static bool IsInternetAvailable()
        {
            var profile = NetworkInformation.GetInternetConnectionProfile();
            if ((profile != null) && (profile.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess))
                return true;
            else
                return false;
        }
    }
}
